package com.community.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.dto.ProductSales;
import com.community.pojo.Product;
import com.community.service.IProductService;
import com.community.utils.PageUtils;
import com.community.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@CrossOrigin
@Controller
@RequestMapping("/community/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     *  2024年6月5日14:07:16 ：
     * Fly:查询  商品销售排列（Top8) 如果小于八那就 数据库有几个就显示几个
     */
    @RequestMapping("/productSalesTop8")
    @ResponseBody
    public ProductSales productSalesTop8() {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("sales").last("limit 8");

        List<Product> top8SalesList = productService.list(queryWrapper);

        // 1.获取产品名称列表
        // 用于存储最长名称的长度
        int maxLength = 0;
        List<String> productNames = new ArrayList<>();
        List<Integer> productSales1 = new ArrayList<>();

        // 2.找到最长的产品名称的长度
        for (Product product : top8SalesList) {
            int length = product.getName().length();
            if (length > maxLength) {
                maxLength = length;
            }
        }

        // 3.定义一个计量器
    /*    int index = 1;
        for (Product product : top8SalesList) {
            productNames.add(product.getName()+"  "+(index++));
            productSales1.add(product.getSales());
        }*/

        // 3.定义一个计量器
        int index = 1;
        for (Product product : top8SalesList) {
            String name = product.getName();
            // 计算需要添加的空格数，最大的名称长度减去当前名称的长度
            int spacesToAdd = maxLength - name.length();
            StringBuilder formattedName = new StringBuilder(name);

            // 添加空格
            for (int i = 0; i < spacesToAdd; i++) {
                formattedName.append(" ");
            }

            // 在所有空格后添加索引
            formattedName.append(" ").append(index);

            // 将格式化后的名称添加到列表
            productNames.add(formattedName.toString());

            // 将销售量添加到列表
            productSales1.add(product.getSales());

            // 递增索引
            index++;
        }

        ProductSales productSales = new ProductSales();
        productSales.setXData(productNames);
        productSales.setYData(productSales1);

        return productSales;
    }



    /**
     * 查询所有商品
     */
    @RequestMapping("/list")
    @ResponseBody
    public PageUtils<Product> productList(int pageNo, int pageSize,@RequestBody ProductVo vo) {
       return this.productService.searchProduct(pageNo,pageSize,vo);

    }

    @RequestMapping("/updateOnOff")
    @ResponseBody
    public Object updateOnOff(int id) {
        Product product = this.productService.getById(id);
        if (product != null) {
            product.setOnOff(0);
            product.setStock(0);
            productService.updateById(product);
        }
        return "下架成功";
    }
    @RequestMapping("/updateUpOff")
    @ResponseBody
    public Object updateUpOff(int id,int stock) {
        Product product = this.productService.getById(id);
        if (product != null) {
            product.setOnOff(1);
            product.setStock(stock);
            productService.updateById(product);
        }
        return "上架成功";
    }

    @RequestMapping("/queryById")
    @ResponseBody
    public Object queryById(int id){
        return this.productService.getById(id);
    }

    @RequestMapping("/updateById")
    @ResponseBody
    public Object updateById(@RequestBody Product product){
        return this.productService.updateById(product);
    }

     //商品图片文件上传
     @RequestMapping("/myupload")
     @ResponseBody
     public String myupload(@RequestParam("file") MultipartFile file){
        //将file源文件对象 保存到图片服务器，并返回图片在服务器的地址
         System.out.println(file);
         //获取源文件名
         String originalFilename = file.getOriginalFilename();
         //截取后缀名
         String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
         //新文件名要唯一
         String newFileName = UUID.randomUUID().toString()+suffix;
         //目标文件对象
         File dir = new File("C:\\myimgs/product/");
         if (!dir.exists()){
            dir.mkdir();
         }
         File destFile = new File(dir,newFileName);
         try {
             //文件写入
             file.transferTo(destFile);
         }catch (IOException e){
             e.printStackTrace();
         }
        return "http://localhost:9000/images/product/"+newFileName;
     }



    //查询所有商品
    @RequestMapping("/queryOnOff")
    @ResponseBody
    public PageUtils<Product> queryProduct(int pageNo, int pageSize,@RequestBody ProductVo vo) {
        return this.productService.queryOnOff(pageNo,pageSize,vo);
    }
    //添加新商品
    @RequestMapping("/addProduct")
    @ResponseBody
    public Object addProduct(@RequestBody Product product){
        //上架库存
       product.setStock(0);
       //是否上架;0:未上架,1:已上架
       product.setOnOff(0);
       //是否删除;C001-1:未删除,C001-2:已删除
       product.setStatus("C001-1");

       productService.save(product);

        return "添加成功";
    }
    /**
     * 根据商品名称查询商品  根据名字
     * @param vo
     * @return
     */
    @RequestMapping("/search")
    @ResponseBody
    public List<Product> show(@RequestBody ProductVo vo) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        if (vo != null) {
            if (!StringUtils.isEmpty(vo.getSearch_name())) {
                wrapper.eq("name", vo.getSearch_name());
            }
        }
        List<Product> show = productService.list(wrapper);
        return show;
    }
    /**
     * 查询所有商品  带条件
     */
    @RequestMapping("/list2")
    @ResponseBody
    public List<Product> productList2(@RequestBody ProductVo vo) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        if (vo != null) {
            if (!StringUtils.isEmpty(vo.getSearch_name())) {
                wrapper.eq("name", vo.getSearch_name());
            }
        }
        return productService.list(wrapper);
    }
    /**
     * 查所有不带添加
     * @return
     */
    @RequestMapping("/list3")
    @ResponseBody
    public List<Product> productList3() {
        return productService.list();
    }
    @RequestMapping("/addCart")
    @ResponseBody
    public boolean addCart(@RequestBody Product product) {
        product.setOnOff(1);
        return productService.updateById(product);
    }
    /**
     * 查询所有的已上架的商品
     * @return
     */
    @RequestMapping("/list4")
    @ResponseBody
    public List<Product> productList4() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("on_off",1);
        return productService.list(wrapper);
    }
    /**
     * 移除购物车
     * @return
     */
    @RequestMapping("/list5")
    @ResponseBody
    public boolean productList5(@RequestBody Product product) {
        System.out.println("product++++"+product);
        product.setOnOff(0);
        return productService.updateById(product);
    }
    //删除商品信息(将对应商品的状态改为已删除)
    @RequestMapping("/deleteById")
    @ResponseBody
    public Object deleteById(int id){
        Product product = this.productService.getById(id);
        if (product != null) {
            //是否删除;C001-1:未删除,C001-2:已删除
            product.setStatus("C001-2");
            productService.updateById(product);
        }
        return "删除成功";
    }

}
